import Taro, { Component } from '@tarojs/taro'
import { setGlobalData, getGlobalData, getAllGlobalData } from './global_data.js'
import allExtrance from './allExtrance'
import taroRequest from './taroRequest/taroRequest'

// 预防登录死循环
function isLoginLoop() {
  const globalData = getAllGlobalData()

  if (++globalData.loginCounter >= 3) {
    globalData.loginCounter = 0
    return true
  }

  return false
}


export default (options) => {
  return new Promise((resolve, reject) => {
    Taro.login()
      .then(res => {
        let url = 'https://api.banchengyun.com/zp/v1/' + options + '/Login/login?code=' + res.code
        taroRequest
          .request({
            url: url,
            needLogin: false
          })
          .then(res => {
            if (!options) {
              return resolve(res)
            }

            if (!isLoginLoop()) {
              taroRequest
                .request(options)
                .then(res => { resolve(res) })
                .catch(err => { reject(err) })
            } else {
              allExtrance.util.Taro.showToast('登录重复失败')
              reject(res)
            }
          })
          .catch(res => {
            if (!options) {
              return reject(res)
            }

            if (res && res.data && res.data.status === 2) {
              // 监听非静默授权
              allExtrance.emitter.once('getUserInfo', (userInfo) => {
                taroRequest
                  .request(options)
                  .then(res => { resolve(res) })
                  .catch(err => { reject(err) })
              })
              Taro.navigateTo({
                url: allExtrance.config.loginPage
              })
            } else {
              allExtrance.util.Taro.showToast('登录请求失败')
              reject(res)
            }
          })
      })
      .catch(err => {
        allExtrance.util.Taro.showToast('获取登录码失败')
        reject(err)
      })
  })
}